package com.example;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerSchemaStatVisitor;
import com.alibaba.druid.util.JdbcConstants;
import com.alibaba.druid.stat.TableStat;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;
import java.util.Map;

public class SqlServerDruidParser {

    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("用法: java -jar druid-sqlserver-parser.jar <sql-directory-or-file>");
            System.exit(1);
        }

        Path path = Paths.get(args[0]);
        if (!Files.exists(path)) {
            System.err.println("路径不存在: " + path);
            System.exit(2);
        }

        try {
            if (Files.isDirectory(path)) {
                Files.walk(path)
                        .filter(p -> p.toString().toLowerCase().endsWith(".sql"))
                        .forEach(SqlServerDruidParser::processFile);
            } else {
                processFile(path);
            }
        } catch (IOException e) {
            System.err.println("遍历文件时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void processFile(Path file) {
        System.out.println("---- 解析文件: " + file + " ----");
        String sql;
        try {
            byte[] bytes = Files.readAllBytes(file);
            sql = new String(bytes, StandardCharsets.UTF_8);
        } catch (IOException e) {
            System.err.println("读取文件失败: " + file + " -> " + e.getMessage());
            return;
        }

        if (sql.trim().isEmpty()) {
            System.out.println("文件为空或仅包含空白: " + file);
            return;
        }

        try {
            List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, JdbcConstants.SQL_SERVER);

            System.out.println("解析出语句数量: " + stmtList.size());
            int idx = 1;
            for (SQLStatement stmt : stmtList) {
                System.out.println();
                System.out.println(">>> 语句 #" + (idx++) + " 原始/格式化: ");
                System.out.println(SQLUtils.toSQLString(stmt, JdbcConstants.SQL_SERVER));

                // 使用 SQL Server 专用的 SchemaStatVisitor 来获取表/列/条件等
                SQLServerSchemaStatVisitor visitor = new SQLServerSchemaStatVisitor();
                stmt.accept(visitor);

                System.out.println("  表:");
                for (Map.Entry<TableStat.Name, TableStat> e : visitor.getTables().entrySet()) {
                    TableStat.Name tname = e.getKey();
                    TableStat ts = e.getValue();
                    System.out.println("    - " + tname + " 信息: " + ts.toString()); // 修改此处
                }

                System.out.println("  列:");
                visitor.getColumns().forEach(col -> {
                    System.out.println("    - " + col.getTable() + "." + col.getName());
                });

                System.out.println("  条件/Where/关联等:");
                visitor.getConditions().forEach(cond -> {
                    System.out.println("    - " + cond);
                });

                System.out.println("  OrderBy:");
                visitor.getOrderByColumns().forEach(o -> System.out.println("    - " + o));

                // 也可以输出别的信息，例如 groupBy、functions 等
            }

        } catch (Exception ex) {
            System.err.println("解析 SQL 失败: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
}